
/**
 * 本地的临时存储的变量
 * {new Map<string, any>}
 */
const storageMap = new Map();

export class Storage {
	/**
	 * 验证Storage是否可用
	 * @returns {Boolean}
	 */
	static ready = () => {
		let result = false;
		uni.setStorageSync('key', 'value');
		const value = uni.getStorageSync('key');
		uni.removeStorageSync('key');
		result = value === 'value';
		return result;
	}

	/**
	 * @description 存储数据
	 * @param {String} key 键值
	 * @param {*} value 值
	 * @param {Number} timestamp 有效时间单位（秒）默认1000天
	 * 
	 * */
	static set = (key, value, timestamp = 86400000) => {
		// 过期时间戳
		const expires = timestamp * 1000 + +new Date();
		// 存储数据
		const data = { expires, value };
		storageMap.set(key, data);
		uni.setStorageSync(key, data);
	}

	/**
	 * @description 提取数据
	 * @param {String} key 键值
	 * @returns {*}
	 * */
	static get = (key) => {
		let data = null;
		if (storageMap.has(key)) {
			data = storageMap.get(key) || null
		} else {
			data = uni.getStorageSync(key) || null;
		}
		if (data) {
			if (data.expires < +new Date()) {
				Storage.del(key);
				return null;
			} else {
				return data.value;
			}
		} else {
			return null;
		}
	}

	/**
	 * @description 删除单条数据
	 * @param  key: string //键值
	 * 
	 * */
	static del = (key) => {
		storageMap.delete(key);
		uni.removeStorageSync(key);
	}

	/**
	 * @description 清除所有数据
	 * 
	 * */
	static clear = () => {
		storageMap.clear();
		uni.clearStorageSync();
	}

}